package com.example.applicationtest.utils

import com.elvishew.xlog.formatter.FormatException
import com.elvishew.xlog.formatter.message.json.JsonFormatter
import org.json.JSONArray
import org.json.JSONObject

class LogJsonFormatter:JsonFormatter {


    private val JSON_INDENT = 4

    override fun format(json: String?): String {
        var formattedString: String? = null
        if (json == null || json.trim { it <= ' ' }.isEmpty()) {
            throw FormatException("JSON empty.")
        }
        formattedString = try {
            if (json.startsWith("{")) {
                val jsonObject = JSONObject(json)
                jsonObject.toString(JSON_INDENT)
            } else if (json.startsWith("[")) {
                val jsonArray = JSONArray(json)
                jsonArray.toString(JSON_INDENT)
            } else {
                throw FormatException("JSON should start with { or [, but found $json")
            }
        } catch (e: Exception) {
            throw FormatException("Parse JSON error. JSON string:$json", e)
        }
        formattedString = "$formattedString"
        formattedString +=""
        return formattedString!!
    }

}